<template>
  <div>
    <Card dis-hover>
      <Form ref="queryForm">
        <Row style="margin-bottom:10px;">
          <Col span="24" style="text-align: right;">
            <Button icon="md-create" style="margin-right:10px;" type="primary"
                    @click="create" :disabled="!hasPermission('Pages.Administration.Users.Create')">
              新建用户
            </Button>
            <Dropdown style="margin-right:10px;" @on-click="handleUploadClick" placement="bottom-end" transfer>
              <Button icon="md-cloud-upload" type="info"
                      :disabled="!hasPermission('Pages.Administration.Users.Import')">从EXCEL导入
                <Icon type="ios-arrow-down"></Icon>
              </Button>
              <DropdownMenu slot="list" v-if="hasPermission('Pages.Administration.Users.Import')">
                <DropdownItem @click.native="uploadUserFile">用户文件上传</DropdownItem>
                <DropdownItem @click.native="downloadTemplate">用户模板下载</DropdownItem>
              </DropdownMenu>
            </Dropdown>
            <Button :disabled="!hasPermission('Pages.Administration.Users.Export')" icon="md-cloud-download"
                    style="margin-right:10px;"
                    type="info" @click="download">导出到EXCEL
            </Button>
            <Button icon="md-search" type="success" @click="getPage">搜索</Button>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="12">
            <FormItem prop="filter" style="width:100%;margin-bottom:10px;">
              <Input v-model="pageRequest.filter" clearable
                     placeholder="在所属单位、用户名、姓名、Email地址、电话号码中搜索" @on-clear="handleClear"></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem prop="date" style="width:100%;margin-bottom:10px;">
              <DatePicker :editable="false" format="yyyy/MM/dd" placeholder="选择创建时间范围" placement="bottom-start"
                          split-panels style="width:100%;" type="daterange"
                          @on-change="dateChange" @on-clear="handleClear" transfer></DatePicker>
            </FormItem>
          </Col>
        </Row>
        <collapse-transition>
          <Row v-if="advancedSearch" :gutter="16">
            <Col span="8">
              <FormItem prop="onlyLockedUsers" style="width:100%">
                <Select v-model="pageRequest.onlyLockedUsers" clearable filterable
                        placeholder="选择锁定状态" @on-clear="handleClear">
                  <Option :key="1" label="已锁定" value="true">
                    <Icon :size="16" color="#ed4014" type="pandx fa fa-lock"></Icon>
                    <span style="margin-left:8px;">已锁定</span>
                  </Option>
                  <Option :key="0" label="未锁定" value="false">
                    <Icon :size="16" color="#c5cec8" type="pandx fa fa-lock">
                    </Icon>
                    <span style="margin-left:8px;">未锁定</span>
                  </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem prop="role" style="width:100%;">
                <Select v-model="pageRequest.role" clearable filterable
                        placeholder="选择角色" @on-clear="handleClear">
                  <Option v-for="item in allRoles" :key="item.id" :label="item.displayName"
                          :value="item.id">
                    <span>{{ item.displayName }}</span>
                    <span style="float:right;color:#ccc;">{{ item.description }}</span>
                  </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem prop="permissions" style="width:100%">

                <Input ref="permissions" v-model="pageRequest.permissionsDisplay" :maxlength="1024" clearable
                       placeholder="请选择权限"
                       readonly @on-clear="handlePermissionClear" @on-focus="handlePermissionFocus">
                </Input>
              </FormItem>
            </Col>
          </Row>
        </collapse-transition>
        <Row>
          <Col span="24">
            <Button v-show="advancedSearch" icon="ios-arrow-up" type="text"
                    @click="toggleClick">隐藏高级搜索
            </Button>
            <Button v-show="!advancedSearch" icon="ios-arrow-down" type="text"
                    @click="toggleClick">显示高级搜索
            </Button>
          </Col>
        </Row>
      </Form>
      <Table :columns="columns" :data="list" :loading="loading" border class="margin-top-10"
             no-data-text="没有任何数据" no-filtered-data-text="没有任何数据" @on-sort-change="sortingChange">
        <template slot="isActive" slot-scope="{row}">
          <Icon v-if="row.isActive" :size="20" :color="$config.color.success" type="pandx fa fa-flash"></Icon>
          <Icon v-if="!row.isActive" :size="20" :color="$config.color.disabled" type="pandx fa fa-flash"></Icon>
        </template>
        <template slot="onlyLockedUsers" slot-scope="{row}">
          <Icon v-if="row.onlyLockedUsers" :size="20" :color="$config.color.error" type="pandx fa fa-lock"></Icon>
          <Icon v-if="!row.onlyLockedUsers" :size="20" :color="$config.color.disabled" type="pandx fa fa-lock"></Icon>
        </template>
        <template slot="actions" slot-scope="{row}">
          <Dropdown placement="bottom-end" transfer @on-click="handleClickActionDropdown">
            <Button size="small" type="primary">
              操作
              <Icon type="ios-arrow-down"></Icon>
            </Button>
            <DropdownMenu slot="list">
              <DropdownItem :name="JSON.stringify({row:row,name:'update'})"
                            :disabled="!hasPermission('Pages.Administration.Users.Update')">更新
              </DropdownItem>
              <DropdownItem :name="JSON.stringify({row:row,name:'unlock'})"
                            :disabled="!hasPermission('Pages.Administration.Users.Unlock')">解锁
              </DropdownItem>
              <template v-if="row.id===$store.state.session.user.id">
                <DropdownItem disabled>删除</DropdownItem>
              </template>
              <template v-else>
                <DropdownItem :name="JSON.stringify({row:row,name:'remove'})"
                              :disabled="!hasPermission('Pages.Administration.Users.Delete')">删除
                </DropdownItem>
              </template>
              <template v-if="row.id===$store.state.session.user.id">
                <DropdownItem disabled divided>特殊权限</DropdownItem>
              </template>
              <template v-else>
                <DropdownItem :name="JSON.stringify({row:row,name:'showPermission'})" divided
                              :disabled="!hasPermission('Pages.Administration.Users.Permission')">特殊权限
                </DropdownItem>
              </template>
              <DropdownItem :name="JSON.stringify({row:row,name:'changePwd'})" divided
                            :disabled="!hasPermission('Pages.Administration.Users.ChangePassword')">修改密码
              </DropdownItem>
            </DropdownMenu>
          </Dropdown>

        </template>
      </Table>
      <Page :current="currentPage" :page-size="pageSize" :page-size-opts="[10,20,30,40]" :total="totalCount"
            class="margin-top-10"
            show-sizer show-total @on-change="pageChange"
            @on-page-size-change="pageSizeChange">

      </Page>
    </Card>
    <user-modal v-if="userModalMount" v-model="userModalShow" :modal-data="userData"
                @save-success="getPage"></user-modal>
    <password-modal v-if="passwordModalMount" v-model="passwordModalShow"
                    :modal-data="passwordData"></password-modal>
    <permission-modal v-if="permissionModalMountForSearch" v-model="permissionModalShowForSearch"
                      :modal-data="permissionDataForSearch"
                      @on-save="handlePermissionConfirmForSearch"></permission-modal>
    <permission-modal v-if="permissionModalMountForList" v-model="permissionModalShowForList"
                      :modal-data="permissionDataForList"
                      @on-save="handlePermissionConfirmForList"></permission-modal>
    <user-file-upload v-if="uploadModalMount" v-model="uploadModalShow" :modal-data="uploadData"></user-file-upload>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import PageRequest from '@/store/entities/page-request';
import Util from '@/lib/util';
import Ajax from '@/lib/ajax';
import CollapseTransition from '@/components/common/collapse-transition';
import UserModal from '@/views/administration/user/modal/user-modal.vue';
import PermissionModal from '@/views/administration/user/modal/permission-modal.vue';
import PasswordModal from '@/views/administration/user/modal/password-modal.vue';
import UserExpand from '@/components/expand/user-expand.vue';
import UserClass from '@/store/entities/administration/user/user';
import UserFileUpload from '@/views/administration/user/modal/user-file-upload.vue';

class PageUserRequest extends PageRequest {
  filter: string = '';
  sorting: string = '';
  role?: number;
  isActive: any[] = [];
  gender: any[] = [];
  onlyLockedUsers?: boolean;
  permissions: string[] = [];
  permissionsDisplay: string;
  startTime: string = '1900-01-01 00:00:00';
  endTime: string = '2099-12-31 23:59:59';
}

@Component({
  components: {
    UserFileUpload,
    UserExpand,
    PasswordModal,
    UserModal,
    PermissionModal,
    CollapseTransition,
  },
})
export default class User extends AbpBase {
  name: string = 'User';


  advancedSearch: boolean = false;
  pageRequest: PageUserRequest = new PageUserRequest();

  userModalMount: boolean = false;
  userModalShow: boolean = false;
  userData: any;

  permissionModalMountForSearch: boolean = false;
  permissionModalShowForSearch: boolean = false;
  permissionDataForSearch: any;

  permissionModalMountForList: boolean = false;
  permissionModalShowForList: boolean = false;
  permissionDataForList: any;

  passwordModalMount: boolean = false;
  passwordModalShow: boolean = false;
  passwordData: any;

  uploadModalMount: boolean = false;
  uploadModalShow: boolean = false;
  uploadData: any;

  headers: any = {Authorization: 'Bearer ' + window.abp.auth.getToken()};

  columns = [
    {
      type: 'expand',
      width: 30,
      render: (h: any, params: any) => {
        return h(UserExpand, {
          props: {
            row: params.row,
          },
        }, []);
      },
    },
    {
      title: '所属单位',
      key: 'organizationUnit',
      align: 'center',
      width: 180,
      render: (h: any, params: any) => {
        return h('span', {}, params.row.organizationUnits.map(el => el.displayName).join('，'));
      },
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',

    },
    {
      title: '用户名',
      key: 'userName',
      align: 'center',
      width: 120,
      sortable: this.$config.sorting.administration.user,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
    },
    {
      title: '姓名',
      key: 'name',
      align: 'center',
      width: 100,
      sortable: this.$config.sorting.administration.user,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
    },
    {
      title: '性别',
      key: 'gender',
      align: 'center',
      render: (h: any, params: any) => {
        if (params.row.gender) {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.info,
              type: 'pandx fa fa-mars',
            },
          }, []);
        } else {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.warning,
              type: 'pandx fa fa-venus',
            },
          }, []);
        }
      },
      width: 90,
      filters: [
        {
          label: '男',
          value: 1,
        }, {
          label: '女',
          value: 0,
        },
      ],
      filterRemote: (array) => {
        this.pageRequest.gender = array;
        this.getPage();
      },
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
    },
    {
      title: '角色',
      key: 'roles',
      align: 'center',
      render: (h: any, params: any) => {
        return h('span', {}, params.row.roles.map(el => el.roleName).join('，'));
      },
      ellipsis: true,
      minWidth: 200,
      tooltip: true,
      resizable: true,
      tooltipTheme: 'dark',
    },
    {
      title: '激活',
      key: 'isActive',
      align: 'center',
      slot: 'isActive',
      width: 90,
      filters: [
        {
          label: '已激活',
          value: true,
        }, {
          label: '未激活',
          value: false,
        },
      ],
      filterRemote: (array) => {
        this.pageRequest.isActive = array;
        this.getPage();
      },
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
    },
    {
      title: '锁定',
      key: 'onlyLockedUsers',
      align: 'center',
      slot: 'onlyLockedUsers',
      width: 90,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
    },
    {
      title: '创建时间',
      key: 'creationTime',
      align: 'center',
      width: 180,
      sortable: this.$config.sorting.administration.user,
      render: (h: any, params: any) => {
        return h('span', {}, Util.getTime(params.row.creationTime));
      },
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
    },
    {
      title: '操作',
      width: 110,
      slot: 'actions',
      align: 'center',
    },
  ];


  get allRoles() {
    return this.$store.state.role.allRoles;
  }

  get list() {
    return this.$store.state.user.list;
  }

  get loading() {
    return this.$store.state.user.loading;
  }

  get pageSize() {
    return this.$store.state.user.pageSize;
  }

  get totalCount() {
    return this.$store.state.user.totalCount;
  }

  get currentPage() {
    return this.$store.state.user.currentPage;
  }

  get excelFile() {
    return this.$store.state.user.excelFile;
  }



  async create() {
    this.userData = {data: null, update: false};
    this.userModalMount = true;
    this.$nextTick(() => {
      this.userModalShow = true;
    });
  }

  toggleClick() {
    this.advancedSearch = !this.advancedSearch;
  }

  handleClear() {
    this.getPage();
  }

  async handleClickActionDropdown(name: string) {
    const temp: any = JSON.parse(name);
    switch (temp.name) {
      case 'update':
        await this.update(temp.row);
        break;
      case 'remove':
        await this.remove(temp.row);
        break;
      case 'changePwd':
        this.changePwd(temp.row);
        break;
      case 'unlock':
        await this.unlock(temp.row);
        break;
      case 'showPermission':
        await this.showPermission(temp.row);
        break;
    }
  }

  async pageChange(page: number) {
    this.$store.commit('user/setCurrentPage', page);
    await this.getPage();
  }

  async pageSizeChange(pageSize: number) {
    this.$store.commit('user/setPageSize', pageSize);
    await this.getPage();
  }

  async sortingChange(sorting: any) {
    if (sorting.column.sortable === 'custom') {
      if (sorting.order === 'asc' || sorting.order === 'desc') {
        this.pageRequest.sorting = sorting.key + ' ' + sorting.order;
      }
      await this.getPage();
    }
  }

  async download() {
    await this.$store.dispatch({
      type: 'user/obtainUsersToExcel',
      data: this.pageRequest,
    });
    if(this.hasPermission("Pages.Files.Download")){
      Util.downloadWithToken('/api/File/DownloadTempFile?fileType=' + this.excelFile.fileType + '&fileToken=' + this.excelFile.fileToken + '&fileName=' + this.excelFile.fileName, this.excelFile.fileName, this.excelFile.fileType);
    }else{
      this.$Message.error({
        background: true,
        content: '下载失败，缺少文件下载权限',
        duration: this.$config.duration,
      });
    }
  }

  downloadTemplate() {
    location.href = 'templates/user_template.xlsx';
  }

  uploadUserFile() {
    this.uploadData = {};
    this.uploadModalMount = true;
    this.$nextTick(() => {
      this.uploadModalShow = true;
    });
  }



  handleUploadClick(name: string) {
    switch (name) {
      case 'upload':
        break;
      case 'download':
        break;
    }
  }

  async remove(row: any) {
    this.$M.confirm({
      title: '系统提示',
      content: '确定要删除用户 ' + row.userName + ' 吗？',
      onOk: async () => {
        await this.$store.dispatch({
          type: 'user/deleteUser',
          data: row,
        });
        this.$Message.success({
          background: true,
          content: '用户 ' + row.userName + ' 已删除成功',
          duration: this.$config.duration,
        });
        await this.getPage();
      },

      onCancel: () => {
      },
    });
  }

  async unlock(row: any) {
    this.$M.confirm({
      title: '系统提示',
      content: '确定要解锁用户 ' + row.userName + ' 吗？',
      onOk: async () => {
        await this.$store.dispatch({
          type: 'user/unlockUser',
          data: row,
        });
        this.$Message.success({
          background: true,
          content: '用户 ' + row.userName + ' 已解锁成功',
          duration: this.$config.duration,
        });
        await this.getPage();
      },
      onCancel: () => {

      },
    });
  }

  async update(row: any) {
    await this.$store.dispatch({
      type: 'user/getUserForEdit',
      data: row,
    });
    await this.$store.dispatch({
      type: 'user/getProfilePictureByUser',
      data: this.$store.state.user.userForEdit.user,
    });
    this.userData = {data: row, update: true};
    this.userModalMount = true;
    this.$nextTick(() => {
      this.userModalShow = true;
    });
  }

  async changePwd(row: any) {
    this.passwordData = {data: row};
    this.passwordModalMount = true;
    this.$nextTick(() => {
      this.passwordModalShow = true;
    });
  }

  async handlePermissionFocus() {
    await this.$store.dispatch({
      type: 'permission/getAllPermissions',
    });
    this.permissionDataForSearch = {user: null, selectedNodes: this.pageRequest.permissions};
    this.permissionModalMountForSearch = true;
    this.$nextTick(() => {
      this.permissionModalShowForSearch = true;
    });
  }

  async showPermission(row: any) {
    await this.$store.dispatch({
      type: 'permission/getAllPermissions',
    });
    await this.$store.dispatch({
      type: 'user/getUserPermissionsForEdit',
      data: row,
    });

    this.permissionDataForList = {
      user: row,
      selectedNodes: this.$store.state.user.permissionForEdit.grantedPermissionNames
    };
    this.permissionModalMountForList = true;
    this.$nextTick(() => {
      this.permissionModalShowForList = true;
    });
  }

  handlePermissionConfirmForSearch(selectedNodes: any, user: any) {
    this.pageRequest.permissionsDisplay = '选择了 ' + selectedNodes.length + ' 个权限';
    this.pageRequest.permissions = selectedNodes.map(item => {
      return item.name;
    });
  }

  async handlePermissionConfirmForList(selectedNodes: any, user: any) {
    await this.$store.dispatch({
      type: 'user/updateUserPermissions',
      data: {
        id: user.id,
        grantedPermissionNames: selectedNodes.map(item => {
          return item.name;
        }),
      },
    });
    this.$Message.success({
      background: true,
      content: '用户 ' + user.userName + ' 的特殊权限已更新成功',
      duration: this.$config.duration,
    });
  }

  handlePermissionClear() {
    this.pageRequest.permissions = [];
    this.getPage();
  }



  dateChange(date: any[]) {
    this.pageRequest.startTime = (date[0] === '' ? '1900-01-01' : date[0]) + ' 00:00:00';
    this.pageRequest.endTime = (date[1] === '' ? '2099-12-31' : date[1]) + ' 23:59:59';
  }

  async getPage() {
    this.pageRequest.maxResultCount = this.pageSize;
    this.pageRequest.skipCount = (this.currentPage - 1) * this.pageSize;
    await this.$store.dispatch({
      type: 'user/obtainUsers',
      data: this.pageRequest,
    });
  }


  async created() {
    await this.getPage();
    await this.$store.dispatch({
      type: 'role/getAllRoles',
    });
  }
}
</script>

<style lang="less" scoped>

</style>
